<?php
/**
 * Created by PhpStorm.
 * User: Min
 * Date: 2018/1/25
 * Time: 20:32
 */

namespace App\Services\Goods;


use App\Repositories\Category\CategoryRepository;
use App\Repositories\Goods\GoodsRepository;
use App\Repositories\Users\UsersRepository;
use App\Services\Category\CategoryService;
use App\Services\PromoteService;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class GoodsSearchService {

    /**
     * @var OpenSearchService
     */
    protected $openSearchService;

    /**
     * @var UsersRepository
     */
    protected $usersRepository;

    /**
     * @var CategoryService
     */
    protected $categoryService;

    /**
     * @var
     */
    protected $goodsRepository;

    /**
     * @var
     */
    protected $goodsService;

    /**
     * 仓库id
     * @var int
     */
    protected $wid = 8;

    /**
     * 用户等级
     * @var int
     */
    protected $userRank = 1;

    /**
     * 分类Id列表
     * @var
     */
    protected $catIdList;

    /**
     * 分类id （一级分类id）
     * @var
     */
    protected $catId;

    /**
     * 子分类id 多个用 '|'分隔  如 356|1128
     * @var
     */
    protected $catChildId;

    /**
     * 产地（筛选） 多个用 '|'分隔  如 香港|俄罗斯
     * @var
     */
    protected $origin;

    /**
     * 品牌id（筛选） 多个用 '|'分隔  如 356|1128
     * @var
     */
    protected $brandId;

    /**
     * 排序字段（价格：shop_price ；评论：comment ）
     * @var
     */
    protected $sortField;

    /**
     * 排序类型（1:升序；2：降序）
     * @var string
     */
    protected $sortType = '-';

    /**
     * @var int
     */
    protected $startOffset = 0;

    /**
     * 搜索关键词
     * @var
     */
    protected $keyword;

    /**
     * GoodsSearchService constructor.
     * @param CategoryService $categoryService
     * @param OpenSearchService $openSearchService
     * @param GoodsRepository $goodsRepository
     * @param PromoteService $promoteService
     * @param UsersRepository $usersRepository
     */
    public function __construct(CategoryService $categoryService,
                                OpenSearchService $openSearchService,
                                GoodsRepository $goodsRepository,
                                GoodsService $goodsService,
                                UsersRepository $usersRepository)
    {
        $this->openSearchService = $openSearchService;
        $this->categoryService = $categoryService;
        $this->usersRepository = $usersRepository;
        $this->goodsRepository = $goodsRepository;
        $this->goodsService = $goodsService;
    }

    /**
     * @author Min
     * @param $name
     * @param $value
     * @return $this
     */
    public function setParams($name, $value)
    {
        $this->$name = $value;
        return $this;
    }

    /**
     * @author Min
     * @param $name
     * @return mixed
     */
    public function getParam($name){
        return $this->$name;
    }

    /**
     * @author Min
     * @param array $params
     * @return $this
     */
    public function config(array $params){
        if(empty($params)){
            throw new NotFoundHttpException('配置有误');
        }

        foreach ($params as $key => $val) {
            $this->setParams($key, $val);
        }
        return $this;
    }

    public function getSearchGoodsList($uid = 0)
    {
        $searchList = $this->getSearchList();

        $goodsIds = $this->getGoodsIds($searchList['items']);

        $goodsList = $this->goodsRepository->getSearchGoodsByIid($goodsIds, $uid, $this->wid);

        $goodsList = $this->goodsService->formatGoodsTransformList($goodsList);

        return $goodsList;

    }

    /**
     * 获取搜索结果
     * @author Min
     * @return bool|mixed
     */
    protected function getSearchList()
    {
        if (empty($this->keyword) && empty($this->catId)) {
            return false;
        }

        //不传关键词，用catId查询相应分类名称
        if ($this->catId && !$this->keyword) {
            $this->keyword = $this->categoryService->getCatNameByCatId($this->catId);
        }

        //处理排序
        $sort = $this->getSortParam($this->sortField, $this->sortType);

        //处理分类筛选
        if ($this->catId) {
            $this->openSearchService->catId = $this->catIdList = $this->getSonCatId($this->catId);
        }

        //处理子分类筛选
        if ($this->catChildId) {
            $this->openSearchService->catId = $this->catChildId;
        }

        //产地筛选
        $this->openSearchService->origin = $this->origin;

        //品牌筛选
        $this->openSearchService->brandId = $this->brandId;

        //仓库id
        $this->openSearchService->wid = $this->wid;

        $searchList = $this->openSearchService->getSearchList($this->keyword, $this->startOffset, $sort);

        if (empty($searchList['items'])) {
            throw new NotFoundHttpException('没有数据', null, 500);
        } else {
            return $searchList;
        }

    }

    /**
     * @author Min
     * @param $data
     * @return array
     */
    protected function getGoodsIds($data){
        $idList = array();
        foreach ($data as $key=>$value) {
            if ($value['goods_id']) {
                $idList[] = $value['goods_id'];
            }
        }
        return implode(',', $idList);
    }

    /**
     * 包含分类
     * @author Min
     * @param string $key
     * @return array
     */
    public function getCategoryId($key = 'get_category')
    {
        $cat_id_list = $this->openSearchService->getCategoryId($this->keyword, $this->catIdList, $key);

        //获取父级分类
        $res = $this->categoryService->getCategoryParentCatId($cat_id_list);
        return tree_data($res);
    }

    /**
     * 包含产地
     * @author Min
     * @return array
     */
    public function getOriginList()
    {
        return $this->openSearchService->getOrigin($this->keyword);
    }

    /**
     * 获取包含品牌
     * @author Min
     * @return array
     */
    public function getBrandList()
    {
        return $this->openSearchService->getBrand($this->keyword);
    }

    /**
     * 获取当前分类的所有子分类id
     * @author Min
     * @param $catId
     * @return int|string
     */
    protected function getSonCatId($catId)
    {
        if (!$catId) {
            return 0;
        }

        $id_list = $this->categoryService->getAllSubCateId($catId);
        return implode('|',$id_list);
    }

    /**
     * 获取排序参数
     * @author Min
     * @param string $sortField
     * @param string $sortType
     * @return array
     */
    protected function getSortParam($sortField='', $sortType='-')
    {
        if (!$sortField) {
            return [];
        }

        $field = $sortField == 'shop_price' ? ($this->userRank == 2 ? 'vip_money' : 'money') : 'comment_conut';

        return [
            'field' => $field,
            'sort' => $sortType
        ];
    }

    /**
     * @author Min
     * @param $sortField
     * @param $sortType
     * @return int
     */
    protected function getSort($sortField, $sortType)
    {
        $sort = 0;
        if ($sortField=='shop_price' && $sortType==1) {
            $sort = 1;
        }

        if ($sortField=='shop_price' && $sortType==2) {
            $sort = 2;
        }

        if ($sortField=='comment' && $sortType==1) {
            $sort = 3;
        }

        if ($sortField=='comment' && $sortType==2) {
            $sort = 4;
        }

        return $sort;
    }



}